import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/LoadToast.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/SetPower.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/ShowToast.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/requestUrl.dart';
import 'package:shared_preferences/shared_preferences.dart';

/**
 * Creat For 11643
 * CreatTime 2022/12/2
 * Description:
 */
class EntryKu extends StatefulWidget {
  const EntryKu({Key? key}) : super(key: key);

  @override
  _EntryKuState createState() => _EntryKuState();
}

class _EntryKuState extends State<EntryKu> {
  //是否正在读取中
  var IsReading = false;
  //手持机是否初始化成功
  var IsInit = "false";
  //扫描器打卡状态
  var IsOpen = "false";
  //原生主动向flutter发送数据通道
  static const channel = const BasicMessageChannel(
      'com.flutter.BasicMessageChannel', StandardMessageCodec());
  ///定义一个通道,flutter调用原生方法
  static const platform = const MethodChannel('com.RfidRead.rfidread');
  ///Widget 选择仓库组件数组
  List<PopupMenuEntry<String>> WIdgetCangKu = [];
  ///仓库数组
  var CangKuList = [];
  ///仓库选择的id
  String CangKuId="";
  ///仓库
  TextEditingController CangKuController = new TextEditingController();
  ///资产类别
  TextEditingController GoodsTypeController = new TextEditingController();
  ///资产类别数组
  var GoodsTypeList = [];
  ///资产类别选择的id
  String GoodsTypeId="";
  ///Widget 选择仓库组件数组
  List<PopupMenuEntry<String>> WIdgetGoodsType = [];
  ///EPC列表
  List EpcList=[];
  String Token="";
  String ApiUrl="";
  ///资产列表
  List GoodsList=[];
  ///页面加载
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero,() async {
      final SharedPreferences sharedPreferences =
      await SharedPreferences.getInstance();
      // 获取本地ip地址
      ApiUrl =(await sharedPreferences.getString('ApiUrl'))!;
      // 获取本地ip地址
      Token = sharedPreferences.getString('Token')!;
      ///获取仓库
      GetCangKu();
      ///获取资产类别
      GetType();
      InitRfid();
      setState(() {
      });
    });

  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if(IsInit=="true"){
      DisScan();
      DisposeRFID();
    }
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("入库",style: TextStyle(fontSize: 15),),
          actions: [
            IconButton(
                onPressed: () {
                  //  点击进去设置功率页面
                  Navigator.push(
                      context, MaterialPageRoute(builder: (context) => SetPower(SetPowerType: "EntryKuPower",)));
                },
                icon: Icon(Icons.settings)),
          ],
        ),
        body:Column(
          children: [
            // 资产类别、
            Container(
              padding: EdgeInsets.only(left: 15, right: 15),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    child: Text("资产类别："),
                  ),
                  Expanded(
                      child: Container(
                        child: PopupMenuButton<String>(
                          child: TextField(
                            enabled: false,
                            controller: GoodsTypeController,
                            decoration: InputDecoration(
                                hintText: "请选择资产类别",
                                hintStyle: TextStyle(fontSize: 13),
                                suffixIcon: Icon(Icons.arrow_drop_down)),
                          ),
                          itemBuilder: (context) {
                            return WIdgetGoodsType;
                          },
                          onSelected: (value) {
                            print(value);
                            for(var i = 0;i<GoodsTypeList.length;i++){
                              if(value==GoodsTypeList[i]['ID']){
                                ///匹配到了相同的oid，将选择的规格赋值显示
                                GoodsTypeController = new TextEditingController(text:GoodsTypeList[i]['Name']);
                                GoodsTypeId = GoodsTypeList[i]['ID'];
                              }
                            }

                            setState(() {});
                          },
                        ),
                      )),
                ],
              ),
            ),
            //仓库
            Container(
              padding: EdgeInsets.only(left: 15, right: 15),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    child: Text("存放地点："),
                  ),
                  Expanded(
                      child: Container(
                        child: PopupMenuButton<String>(
                          child: TextField(
                            enabled: false,
                            controller: CangKuController,
                            decoration: InputDecoration(
                                hintText: "请选择存放地点",
                                hintStyle: TextStyle(fontSize: 13),
                                suffixIcon: Icon(Icons.arrow_drop_down)),
                          ),
                          itemBuilder: (context) {
                            return WIdgetCangKu;
                          },
                          onSelected: (value) {
                            print(value);
                            for(var i = 0;i<CangKuList.length;i++){
                              if(value==CangKuList[i]['ID']){
                                ///匹配到了相同的oid，将选择的规格赋值显示
                                CangKuController = new TextEditingController(text:CangKuList[i]['Name']);
                                CangKuId = CangKuList[i]['ID'];
                              }
                            }
                            setState(() {});
                          },
                        ),
                      )),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.only(left: 15,top: 15),
              alignment: Alignment.centerLeft,
              child: Text("入库列表：",style: TextStyle(fontWeight: FontWeight.w600,fontSize: 17),),
            ),
            //入库列表
            Expanded(
              child: ListView.builder(
                itemCount: GoodsList.length,
                  itemBuilder: (context,index){
                return Container(
                  decoration: BoxDecoration(
                    border: Border(bottom: BorderSide(width: 0.5,color: Colors.black38)),
                  ),
                  padding: EdgeInsets.all(10),
                  child: Text("RFID编码:${GoodsList[index]}")
                );
              }),
            ),
            ///底部按钮
            Container(
              height: 50,
              width: MediaQuery.of(context).size.width - 30,
              child: GridView(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount:3,
                ),
                children: [
                  GestureDetector(
                    child: Container(
                      alignment: Alignment.topCenter,
                      child:   Column(
                        children: [
                          Icon(Icons.wifi,color:IsReading?Colors.red:Colors.black38),
                          Text(IsReading?"停止读取":"开始读取",style: TextStyle(fontSize: 13,color: IsReading?Colors.red:Colors.black38))
                        ],
                      ),
                    ),
                    onTap: (){
                      if(IsReading){
                        //停止读卡
                        StopRead();
                      }else{
                        //读卡
                        ReadRfid();
                      }

                    },
                  ),
                  GestureDetector(
                    child:Container(
                      alignment: Alignment.topCenter,
                      child:   Column(
                        children: [
                          Icon(Icons.delete,color: Colors.orange),
                          Text("清空数据",style: TextStyle(fontSize: 13,color: Colors.orange))
                        ],
                      ),
                    ),
                    onTap: (){
                      if(IsReading){
                        ShowToast().MyToast("请先停止读卡");
                        return;
                      }
                      //  情况数据
                      showAlertDialog();
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      alignment: Alignment.topCenter,
                      child:   Column(
                        children: [
                          Icon(Icons.cloud_upload,color: Colors.green),
                          Text("上传数据",style: TextStyle(fontSize: 13,color: Colors.green))
                        ],
                      ),
                    ),
                    onTap: (){
                      if(IsReading){
                        ShowToast().MyToast("请先停止读卡");
                        return;
                      }
                      //上传入库
                      if(GoodsTypeController.text.isEmpty){
                        ShowToast().MyToast("请请选择资产类别！");
                        return;
                      }
                      if(CangKuController.text.isEmpty){
                        ShowToast().MyToast("请选择存放位置！");
                        return;
                      }
                      if(GoodsList.isEmpty){
                        ShowToast().MyToast("请读取入库资产！");
                        return;
                      }
                      //上传
                      UploadLink();
                    },
                  )
                ],
              ),
            ),
            Container(
              height: 10,
            ),
          ],
        )// This trailing comma makes auto-formatting nicer for build methods.
    );
  }
  //  初始化rfid
  Future<void> InitRfid() async {
    // 加载框
    LoadToast().LoadingToast("初始化中...", context);
    var isinit = await platform.invokeMethod("InitRfid");
    //取出本地保存的功率
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    IsInit = isinit;
    if (isinit == "true") {
      print("初始化成功");
      if (await sharedPreferences.getInt("EntryKuPower") != null) {
        var Power = await sharedPreferences.getInt("EntryKuPower");
        //  设置功率
        bool IsSet = await platform.invokeMethod('SetPower', Power);
        if (IsSet) {
          new ShowToast().MyToast("初始化成功");
        }
      } else {
        //  用系统给用户默认的功率10
        //  设置功率
        bool IsSet = await platform.invokeMethod('SetPower', 20);
        if (IsSet) {
          new ShowToast().MyToast("初始化成功");
          //  保存本地
          await sharedPreferences.setInt("EntryKuPower", 20);
        }
      }
    } else {
      ShowToast().MyToast("初始化失败，请重新进入此页面!");
    }
    // GetLocationList();
    IniListenNative();
    OpenScan();
    print("初始化设备结果$isinit");
  }

  // 读取
  ReadRfid() async {
    IsReading = true;
    setState(() {
    });
    platform.invokeMethod('ReadRfid');
  }

  ReadRfidOne() {
    platform.invokeMethod('ReadRFIDOne');
  }

  // 停止读卡
  StopRead() async {
    IsReading = false;
    setState(() {
    });
    platform.invokeMethod('StopReadRfid');
  }

  // 销毁rfid
  DisposeRFID() {
    IsInit = "false";
    platform.invokeMethod('onDestroy');
  }
  //打开扫描
  OpenScan() async {
    platform.invokeMethod('InitScan');
  }
  //开始扫描
  StartScan() {
    platform.invokeMethod('StartScan');
  }

  //销毁扫描
  DisScan() {
    platform.invokeMethod('DestoryScan');
  }
  //  注册监听原生发送的数据
  IniListenNative() {
    LoadToast().CloseLoading();
    var value;
    channel.setMessageHandler((message) async {
      print("BluDemo已接受到原生主动发出的数据$message");
      value = json.decode(message.toString());
      if (value['Type'] == "Scan") {
      } else if (value['Type'] == "onKeyDown") {
        //  监听摁键摁下
        ReadRfid();
      } else if (value['Type'] == "onKeyUp") {
        //摁键抬起
        StopRead();
      } else if (value['Type'] == "Request") {
      //   原生网络请求
        if(value['Data']!=""&&value['Data']!=null){
        }else{
          GoodsList.add(value['EPC']);
        }
      }else {
        if (value['Epc'] != "") {
          print("RFID编码${value['Epc']}");
          ///判断是否读取重复
          if(!EpcList.contains(value['Epc'])){
            EpcList.add(value['Epc']);
            // GetTagMessage(value['Epc']);
            ///请求原生网络请求
            var data = {
              "ID":value['Epc'],
              "Url":ApiUrl+"/api/AppAssetStock/GetModel",
              "Token":Token
            };
            platform.invokeMethod('GetRfidMessagePost',data);

          }
        }
      }
      setState(() {});
    });
  }

  ///获取仓库
  GetCangKu()async{
    var ResponseData;
    WIdgetCangKu.clear();
    ResponseData = await new requestUrl().CommenRequest(
        '/api/AppWarehouse/Get', 'post', {"limit":99999}, "获取仓库中...", context, false, "application/x-www-form-urlencoded");
    if (ResponseData['code'] == 0) {
      CangKuList = ResponseData['data'];
      for(var i=0;i<CangKuList.length;i++){
        WIdgetCangKu.add(PopupMenuItem<String>(
          value:CangKuList[i]['ID'],
          child: Text('${CangKuList[i]['Name']}'),
        ),);
      }
    } else {
    }
    setState(() {
    });
  }
  ///获取资产类别
  GetType()async{
    var ResponseData;
    WIdgetGoodsType.clear();
    ResponseData = await new requestUrl().CommenRequest(
        '/api/AppAssetCategory/Get', 'post', {"limit":99999}, "获取资产类别中...", context, false, "application/x-www-form-urlencoded");
    if (ResponseData['code'] == 0) {
      GoodsTypeList = ResponseData['data'];
      for(var i=0;i<ResponseData['data'].length;i++){
        WIdgetGoodsType.add(PopupMenuItem<String>(
          value:ResponseData['data'][i]['ID'],
          child: Text('${ResponseData['data'][i]['Name']}'),
        ),);
      }
    } else {
    }
    setState(() {
    });
  }
  //  提交绑定信息
  UploadLink() async {
    var ResponseData;
    ResponseData = await new requestUrl().CommenRequest(
        '/api/AppAssetIn/Add', 'post',
        {
          "RFIDCodes":GoodsList,
          "WarehouseID":CangKuId,
          "AssetCategoryID": GoodsTypeId,
          "Quantity": GoodsList.length,
          "Capacity":1
        }, "入库中...", context, true, "application/x-www-form-urlencoded");
    if (ResponseData['code'] == 0) {
      ShowToast().MyToast("成功入库！");
      setState(() {});
    } else {
      ShowToast().MyToast(ResponseData['msg']);
    }
  }
//  清空数据
  Clear() {
    EpcList.clear();
    GoodsList.clear();
    ShowToast().MyToast("清空成功!");
    setState(() {});
  }
  ///弹窗
  void showAlertDialog() {
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: new Text('警告！'),
            //可滑动
            content: Text("确定要清空数据吗？"),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                  Clear();
                },
              ),
              new FlatButton(
                child: new Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }
}